package com.huanbao.nongwu.controller;

import com.alibaba.fastjson.JSON;
import com.huanbao.common.api.CommonResult;
import com.huanbao.nongwu.pojo.SewageVO;
import com.huanbao.nongwu.pojo.beans.Area;
import com.huanbao.nongwu.pojo.beans.Sewage;
import com.huanbao.nongwu.pojo.beans.Weather;
import com.huanbao.nongwu.service.AreaServiceImpl;
import com.huanbao.nongwu.service.SewageServiceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/* ━━━━━━佛祖保佑━━━━━━
 *                  ,;,,;
 *                ,;;'(    社
 *      __      ,;;' ' \   会
 *   /'  '\'~~'~' \ /'\.)  主
 * ,;(      )    /  |.     义
 *,;' \    /-.,,(   ) \    码
 *     ) /       ) / )|    农
 *     ||        ||  \)
 *     (_\       (_\
 * ━━━━━━永无BUG━━━━━━
 * @author ：zjq
 * @date ：2021/3/24 9:54
 * @description: TODO           站点 直接 copy 老农污 改一改
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 */
@RestController
@RequestMapping("sewage")
public class SewageController {

    @Autowired
    private SewageServiceImpl iSewageService;

    @Autowired
    private AreaServiceImpl iAreaService;

    /**
     * 获取区县坐标信息
     *
     * @throws IOException
     */
    @RequestMapping("/getMapConfig")
    public Map<String, Object> getMapConfig() throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("areaName", "邳州");
        map.put("latitude", 0);
        map.put("longitude", 0);
        map.put("useAreaName", true);
        map.put("areaName", "邳州");
        map.put("zoom", 11);
        return map;
    }


    /**
     * 根据 区域 id  找 站点 数据
     *
     * @param sewageVO
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping("/getsewagebyareaid")
    public CommonResult ajaxGetSewagesByAreaId(@RequestBody SewageVO sewageVO) {
        int areaid = sewageVO.getAreaid() == null ? -1 : sewageVO.getAreaid();
        List<Sewage> sewages = iSewageService.getSewagesByAreaId(areaid);
        return CommonResult.success(sewages);
    }


    /**
     * 查找所有站点 主要用于 实时监控地图 显示站点
     *
     * @return
     */
    @RequestMapping("/getallsewages")
    public CommonResult getallsewages() {
        List<Sewage> sewages = iSewageService.getallsewages();
        return CommonResult.success(sewages);
    }


    /**
     * 获取 天气信息
     *
     * @param sewageVO
     * @return
     */
    @RequestMapping("/getWeather")
    public CommonResult getWeather(@RequestBody SewageVO sewageVO) {

        Sewage sewage = iSewageService.selectByPrimaryKey(sewageVO.getSewageid());
        Area area = iAreaService.selectByPrimaryKey(sewage.getAreaid());

        CloseableHttpClient httpclient = null;
        Weather weather = new Weather();

        try {
            httpclient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet("https://tianqiapi.com/api.php?style=ya&skin=pitaya&city=" + area.getName());
            httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
            httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

            HttpResponse resp = httpclient.execute(httpget);
            String pic = "";
            String temperature = "";
            String weatherName = "";
            if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {
                HttpEntity entity = resp.getEntity();

                String html = EntityUtils.toString(entity);
                Document doc = Jsoup.parse(html);
                Elements elements = doc.select("body div table tr td");

                for (Element ele : elements) {
                    if (ele.attr("align").equals("right")) {
                        String temp[] = ele.text().split(" ");
                        temperature = temp[0];
                        weatherName = temp[1];

                        Elements img = ele.select("div p img");
                        for (Element element : img) {
                            pic = element.attr("src");
                        }
                    }
                    break;
                }
            }

            weather.setCity(area.getName());
            weather.setUrl(pic);
            weather.setTemperature(temperature);
            weather.setWeatherName(weatherName);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return CommonResult.success(weather);
    }

}